import { 
    Document, 
    Packer, 
    Paragraph, 
    TextRun, 
    HeadingLevel, 
    AlignmentType, 
    ImageRun, 
    Table, 
    TableRow, 
    TableCell, 
    BorderStyle,
    WidthType,
    TableLayoutType,
    VerticalAlign,
    UnderlineType,
    LineRuleType
} from 'docx';

/**
 * 将Tiptap JSON转换为Word文档
 * @param {Object} tiptapContent - Tiptap内容对象
 * @param {string} fileName - 文件名
 */
export const convertTiptapToDocx = async (tiptapContent, fileName = '文档') => {
    try {
        // 检查输入数据
        if (!tiptapContent) {
            throw new Error('文档内容为空');
        }
        
        // 确保内容是对象格式
        if (typeof tiptapContent === 'string') {
            try {
                tiptapContent = JSON.parse(tiptapContent);
            } catch (parseError) {
                throw new Error('文档内容格式错误，无法解析JSON');
            }
        }
        
        if (!tiptapContent.content || !Array.isArray(tiptapContent.content)) {
            throw new Error('文档内容格式错误：缺少content数组');
        }
        
        const children = [];
        
        // 遍历Tiptap内容
        tiptapContent.content.forEach((node, index) => {
            const element = convertNodeToDocx(node);
            if (element) {
                // 处理返回数组的情况（如列表）
                if (Array.isArray(element)) {
                    children.push(...element);
                } else {
                    children.push(element);
                }
            }
        });
        
        // 如果没有有效内容，添加一个空段落
        if (children.length === 0) {
            children.push(new Paragraph({
                children: [new TextRun({ text: '文档内容为空' })]
            }));
        }
        
        // 创建Word文档
        const doc = new Document({
            sections: [{
                properties: {},
                children: children
            }]
        });
        
        // 生成文件并下载
        const blob = await Packer.toBlob(doc);
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `${fileName}.docx`;
        link.click();
        URL.revokeObjectURL(url);
        
    } catch (error) {
        throw new Error(`导出失败: ${error.message}`);
    }
};

/**
 * 转换节点为Word元素
 * @param {Object} node - Tiptap节点
 * @returns {Object|null} Word元素
 */
const convertNodeToDocx = (node) => {
    switch (node.type) {
        case 'paragraph':
            return convertParagraph(node);
        case 'heading':
            return convertHeading(node);
        case 'blockquote':
            return convertBlockquote(node);
        case 'bulletList':
        case 'orderedList':
            return convertList(node);
        case 'taskList':
            return convertTaskList(node);
        case 'table':
            return convertTable(node);
        case 'image':
            return convertImage(node);
        case 'codeBlock':
            return convertCodeBlock(node);
        case 'horizontalRule':
            return convertHorizontalRule(node);
        case 'hardBreak':
            return convertHardBreak(node);
        default:
            return null;
    }
};

/**
 * 转换段落
 * @param {Object} node - 段落节点
 * @returns {Paragraph} Word段落
 */
const convertParagraph = (node) => {
    const children = [];
    
    if (node.content) {
        node.content.forEach(child => {
            if (child.type === 'text') {
                const textRun = convertTextRun(child);
                if (textRun) children.push(textRun);
            } else if (child.type === 'hardBreak') {
                children.push(convertHardBreak(child));
            }
        });
    }
    
    return new Paragraph({
        children: children,
        alignment: getAlignment(node.attrs?.textAlign),
        spacing: {
            before: 200,
            after: 200,
            line: 360,
            lineRule: LineRuleType.AUTO
        }
    });
};

/**
 * 转换标题
 * @param {Object} node - 标题节点
 * @returns {Paragraph} Word标题段落
 */
const convertHeading = (node) => {
    const children = [];
    
    if (node.content) {
        node.content.forEach(child => {
            if (child.type === 'text') {
                const textRun = convertTextRun(child);
                if (textRun) children.push(textRun);
            }
        });
    }
    
    return new Paragraph({
        children: children,
        heading: getHeadingLevel(node.attrs?.level),
        alignment: getAlignment(node.attrs?.textAlign),
        spacing: {
            before: 400,
            after: 200,
            line: 360,
            lineRule: LineRuleType.AUTO
        }
    });
};

/**
 * 转换引用块
 * @param {Object} node - 引用块节点
 * @returns {Array} Word段落数组
 */
const convertBlockquote = (node) => {
    const children = [];
    
    if (node.content) {
        node.content.forEach(child => {
            // 直接处理子节点，而不是先转换再修改
            if (child.type === 'paragraph') {
                const paragraphChildren = [];
                
                if (child.content) {
                    child.content.forEach(textChild => {
                        if (textChild.type === 'text') {
                            const textRun = convertTextRun(textChild);
                            if (textRun) paragraphChildren.push(textRun);
                        } else if (textChild.type === 'hardBreak') {
                            paragraphChildren.push(convertHardBreak(textChild));
                        }
                    });
                }
                
                children.push(new Paragraph({
                    children: paragraphChildren,
                    alignment: getAlignment(child.attrs?.textAlign),
                    spacing: {
                        before: 200,
                        after: 200,
                        left: 720,
                        right: 720
                    },
                    border: {
                        left: {
                            color: "CCCCCC",
                            space: 1,
                            style: BorderStyle.SINGLE,
                            size: 6
                        }
                    }
                }));
            } else if (child.type === 'heading') {
                // 处理引用块中的标题
                const headingChildren = [];
                
                if (child.content) {
                    child.content.forEach(textChild => {
                        if (textChild.type === 'text') {
                            const textRun = convertTextRun(textChild);
                            if (textRun) headingChildren.push(textRun);
                        }
                    });
                }
                
                children.push(new Paragraph({
                    children: headingChildren,
                    heading: getHeadingLevel(child.attrs?.level),
                    alignment: getAlignment(child.attrs?.textAlign),
                    spacing: {
                        before: 400,
                        after: 200,
                        left: 720,
                        right: 720
                    },
                    border: {
                        left: {
                            color: "CCCCCC",
                            space: 1,
                            style: BorderStyle.SINGLE,
                            size: 6
                        }
                    }
                }));
            } else {
                // 处理其他类型的节点
                const element = convertNodeToDocx(child);
                if (element) {
                    if (Array.isArray(element)) {
                        // 为数组中的每个段落添加引用样式
                        element.forEach(para => {
                            if (para instanceof Paragraph) {
                                children.push(new Paragraph({
                                    children: para.children,
                                    alignment: para.alignment,
                                    spacing: {
                                        before: 200,
                                        after: 200,
                                        left: 720,
                                        right: 720
                                    },
                                    border: {
                                        left: {
                                            color: "CCCCCC",
                                            space: 1,
                                            style: BorderStyle.SINGLE,
                                            size: 6
                                        }
                                    }
                                }));
                            } else {
                                children.push(para);
                            }
                        });
                    } else {
                        if (element instanceof Paragraph) {
                            children.push(new Paragraph({
                                children: element.children,
                                alignment: element.alignment,
                                spacing: {
                                    before: 200,
                                    after: 200,
                                    left: 720,
                                    right: 720
                                },
                                border: {
                                    left: {
                                        color: "CCCCCC",
                                        space: 1,
                                        style: BorderStyle.SINGLE,
                                        size: 6
                                    }
                                }
                            }));
                        } else {
                            children.push(element);
                        }
                    }
                }
            }
        });
    }
    
    return children;
};

/**
 * 转换列表
 * @param {Object} node - 列表节点
 * @returns {Array} Word段落数组
 */
const convertList = (node) => {
    const children = [];
    let listIndex = 1;
    
    if (node.content) {
        node.content.forEach(listItem => {
            if (listItem.type === 'listItem') {
                // 处理列表项内容
                if (listItem.content) {
                    listItem.content.forEach(child => {
                        if (child.type === 'paragraph') {
                            // 处理段落内容
                            const paragraphChildren = [];
                            
                            if (child.content) {
                                child.content.forEach(textChild => {
                                    if (textChild.type === 'text') {
                                        const textRun = convertTextRun(textChild);
                                        if (textRun) paragraphChildren.push(textRun);
                                    }
                                });
                            }
                            
                            // 添加列表标记
                            const listText = node.type === 'orderedList' ? `${listIndex}. ` : '• ';
                            paragraphChildren.unshift(new TextRun({
                                text: listText,
                                bold: true
                            }));
                            
                            children.push(new Paragraph({
                                children: paragraphChildren,
                                alignment: getAlignment(child.attrs?.textAlign),
                                spacing: {
                                    before: 200,
                                    after: 200,
                                    line: 360,
                                    lineRule: LineRuleType.AUTO
                                }
                            }));
                            
                            listIndex++;
                        }
                    });
                }
            }
        });
    }
    
    return children;
};

/**
 * 转换任务列表
 * @param {Object} node - 任务列表节点
 * @returns {Array} Word段落数组
 */
const convertTaskList = (node) => {
    const children = [];
    
    if (node.content) {
        node.content.forEach(taskItem => {
            if (taskItem.type === 'taskItem') {
                // 处理任务项内容
                if (taskItem.content) {
                    taskItem.content.forEach(child => {
                        if (child.type === 'paragraph') {
                            // 处理段落内容
                            const paragraphChildren = [];
                            
                            if (child.content) {
                                child.content.forEach(textChild => {
                                    if (textChild.type === 'text') {
                                        const textRun = convertTextRun(textChild);
                                        if (textRun) paragraphChildren.push(textRun);
                                    }
                                });
                            }
                            
                            // 添加复选框
                            const checkboxText = taskItem.attrs?.checked ? '☑ ' : '☐ ';
                            paragraphChildren.unshift(new TextRun({
                                text: checkboxText,
                                size: 20
                            }));
                            
                            children.push(new Paragraph({
                                children: paragraphChildren,
                                alignment: getAlignment(child.attrs?.textAlign),
                                spacing: {
                                    before: 200,
                                    after: 200,
                                    line: 360,
                                    lineRule: LineRuleType.AUTO
                                }
                            }));
                        }
                    });
                }
            }
        });
    }
    
    return children;
};

/**
 * 转换表格
 * @param {Object} node - 表格节点
 * @returns {Table|null} Word表格
 */
const convertTable = (node) => {
    // 检查表格是否有内容
    if (!node.content || node.content.length === 0) {
        return null;
    }
    
    const rows = [];
    
    node.content.forEach((tableRow) => {
        if (tableRow.type === 'tableRow') {
            const cells = [];
            
            if (tableRow.content && tableRow.content.length > 0) {
                tableRow.content.forEach((tableCell) => {
                    if (tableCell.type === 'tableCell' || tableCell.type === 'tableHeader') {
                        const cellChildren = [];
                        
                        if (tableCell.content && tableCell.content.length > 0) {
                            tableCell.content.forEach(child => {
                                if (child.type === 'text') {
                                    const textRun = convertTextRun(child);
                                    if (textRun) cellChildren.push(textRun);
                                } else if (child.type === 'paragraph') {
                                    // 处理段落内容
                                    const paragraphChildren = [];
                                    if (child.content) {
                                        child.content.forEach(paraChild => {
                                            if (paraChild.type === 'text') {
                                                const textRun = convertTextRun(paraChild);
                                                if (textRun) paragraphChildren.push(textRun);
                                            }
                                        });
                                    }
                                    if (paragraphChildren.length > 0) {
                                        cellChildren.push(new Paragraph({ children: paragraphChildren }));
                                    }
                                }
                            });
                        }
                        
                        // 如果没有内容，添加一个空段落
                        if (cellChildren.length === 0) {
                            cellChildren.push(new Paragraph({ children: [new TextRun({ text: ' ' })] }));
                        }
                        
                        cells.push(new TableCell({
                            children: cellChildren.length === 1 && cellChildren[0] instanceof Paragraph 
                                ? cellChildren 
                                : [new Paragraph({ children: cellChildren })],
                            verticalAlign: VerticalAlign.CENTER,
                            shading: {
                                fill: tableCell.type === 'tableHeader' ? "F2F2F2" : "FFFFFF",
                                color: "auto"
                            },
                            borders: {
                                top: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
                                bottom: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
                                left: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
                                right: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" }
                            }
                        }));
                    }
                });
            }
            
            // 如果行没有单元格，添加一个空单元格
            if (cells.length === 0) {
                cells.push(new TableCell({
                    children: [new Paragraph({ children: [new TextRun({ text: ' ' })] })],
                    verticalAlign: VerticalAlign.CENTER,
                    shading: { fill: "FFFFFF", color: "auto" },
                    borders: {
                        top: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
                        bottom: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
                        left: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
                        right: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" }
                    }
                }));
            }
            
            rows.push(new TableRow({ children: cells }));
        }
    });
    
    // 如果没有行，返回null
    if (rows.length === 0) {
        return null;
    }
    
    return new Table({
        rows: rows,
        width: {
            size: 100,
            type: WidthType.PERCENTAGE
        },
        layout: TableLayoutType.FIXED,
        borders: {
            top: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
            bottom: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
            left: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
            right: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" }
        }
    });
};

/**
 * 转换图片
 * @param {Object} node - 图片节点
 * @returns {Paragraph} Word图片段落
 */
const convertImage = (node) => {
    return new Paragraph({
        children: [
            new ImageRun({
                data: node.attrs?.src || '',
                transformation: {
                    width: 400,
                    height: 300
                },
                altText: {
                    title: node.attrs?.title || '',
                    description: node.attrs?.alt || ''
                }
            })
        ],
        alignment: AlignmentType.CENTER
    });
};

/**
 * 转换代码块
 * @param {Object} node - 代码块节点
 * @returns {Paragraph} Word代码块段落
 */
const convertCodeBlock = (node) => {
    const children = [];
    
    if (node.content) {
        node.content.forEach(child => {
            if (child.type === 'text') {
                children.push(new TextRun({
                    text: child.text || '',
                    font: 'Courier New',
                    size: 20
                }));
            }
        });
    }
    
    return new Paragraph({
        children: children,
        spacing: {
            before: 200,
            after: 200,
            left: 360,
            right: 360
        },
        shading: {
            fill: "F5F5F5",
            color: "auto"
        },
        border: {
            top: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
            bottom: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
            left: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" },
            right: { style: BorderStyle.SINGLE, size: 1, color: "CCCCCC" }
        }
    });
};

/**
 * 转换水平分割线
 * @param {Object} node - 水平分割线节点
 * @returns {Paragraph} Word分割线段落
 */
const convertHorizontalRule = (node) => {
    return new Paragraph({
        children: [],
        border: {
            bottom: {
                color: "CCCCCC",
                space: 1,
                style: BorderStyle.SINGLE,
                size: 6
            }
        }
    });
};

/**
 * 转换换行
 * @param {Object} node - 换行节点
 * @returns {TextRun} Word换行文本
 */
const convertHardBreak = (node) => {
    return new TextRun({
        text: '\n',
        break: 1
    });
};

/**
 * 转换文本运行
 * @param {Object} node - 文本节点
 * @returns {TextRun} Word文本运行
 */
const convertTextRun = (node) => {
    const options = {
        text: node.text || ''
    };
    
    // 处理文本样式
    if (node.marks) {
        node.marks.forEach(mark => {
            switch (mark.type) {
                case 'bold':
                    options.bold = true;
                    break;
                case 'italic':
                    // 确保斜体属性正确设置
                    options.italic = true;
                    break;
                case 'underline':
                    options.underline = {
                        type: UnderlineType.SINGLE,
                        color: "000000"
                    };
                    break;
                case 'strike':
                    options.strike = true;
                    break;
                case 'code':
                    options.font = 'Courier New';
                    options.size = 20;
                    break;
                case 'link':
                    options.color = "0000FF";
                    options.underline = {
                        type: UnderlineType.SINGLE,
                        color: "0000FF"
                    };
                    break;
                case 'highlight':
                    // 处理高亮颜色
                    const highlightColor = getHighlightColor(mark.attrs?.color);
                    if (highlightColor) {
                        options.highlight = highlightColor;
                    }
                    break;
                case 'textStyle':
                    // 处理文本颜色
                    if (mark.attrs?.color) {
                        options.color = convertColorToHex(mark.attrs.color);
                    }
                    // 处理字体大小
                    if (mark.attrs?.fontSize) {
                        options.size = parseInt(mark.attrs.fontSize) * 2;
                    }
                    // 处理字体族
                    if (mark.attrs?.fontFamily) {
                        options.font = mark.attrs.fontFamily;
                    }
                    break;
                case 'subscript':
                    options.subScript = true;
                    break;
                case 'superscript':
                    options.superScript = true;
                    break;
            }
        });
    }
    
    return new TextRun(options);
};

/**
 * 获取高亮颜色
 * @param {string} color - 颜色值
 * @returns {string} Word高亮颜色
 */
const getHighlightColor = (color) => {
    if (!color) return 'yellow';
    
    const colorMap = {
        // 项目中的高亮颜色变量
        'var(--tt-color-highlight-red)': 'red',
        'var(--tt-color-highlight-orange)': 'yellow',
        'var(--tt-color-highlight-yellow)': 'yellow',
        'var(--tt-color-highlight-green)': 'green',
        'var(--tt-color-highlight-blue)': 'cyan',
        'var(--tt-color-highlight-purple)': 'magenta',
        'var(--tt-color-highlight-pink)': 'magenta',
        'var(--tt-color-highlight-gray)': 'lightGray',
        'var(--tt-color-highlight-brown)': 'darkYellow',
        
        // 十六进制颜色映射
        '#ffe4e6': 'red',
        '#fbe4d4': 'yellow',
        '#fef9c3': 'yellow',
        '#dcfce7': 'green',
        '#e0f2fe': 'cyan',
        '#f3e8ff': 'magenta',
        '#fce7f3': 'magenta',
        '#f8f8f7': 'lightGray',
        '#f4eeee': 'darkYellow'
    };
    
    return colorMap[color] || 'yellow';
};

/**
 * 转换颜色为十六进制
 * @param {string} color - 颜色值
 * @returns {string} 十六进制颜色
 */
const convertColorToHex = (color) => {
    if (!color) return '000000';
    
    // 处理CSS变量 - 根据项目实际的颜色变量
    if (color.startsWith('var(--')) {
        const colorMap = {
            // 文本颜色变量
            'var(--tt-color-text-red)': 'E53E3E',
            'var(--tt-color-text-orange)': 'DD6B20', 
            'var(--tt-color-text-yellow)': 'D69E2E',
            'var(--tt-color-text-green)': '38A169',
            'var(--tt-color-text-blue)': '3182CE',
            'var(--tt-color-text-purple)': '805AD5',
            'var(--tt-color-text-pink)': 'D53F8C',
            'var(--tt-color-text-gray)': '718096',
            'var(--tt-color-text-brown)': '8B4513',
            
            // 高亮颜色变量
            'var(--tt-color-highlight-red)': 'FFE4E6',
            'var(--tt-color-highlight-orange)': 'FBE4D4',
            'var(--tt-color-highlight-yellow)': 'FEF9C3',
            'var(--tt-color-highlight-green)': 'DCFCE7',
            'var(--tt-color-highlight-blue)': 'E0F2FE',
            'var(--tt-color-highlight-purple)': 'F3E8FF',
            'var(--tt-color-highlight-pink)': 'FCE7F3',
            'var(--tt-color-highlight-gray)': 'F8F8F7',
            'var(--tt-color-highlight-brown)': 'F4EEEE'
        };
        return colorMap[color] || '000000';
    }
    
    // 处理HSL格式 - 项目中使用的主要格式
    const hslMatch = color.match(/hsl\((\d+),\s*(\d+)%,\s*(\d+)%\)/);
    if (hslMatch) {
        const h = parseInt(hslMatch[1]);
        const s = parseInt(hslMatch[2]);
        const l = parseInt(hslMatch[3]);
        return hslToHex(h, s, l);
    }
    
    // 处理HSLA格式
    const hslaMatch = color.match(/hsla\((\d+),\s*(\d+)%,\s*(\d+)%,\s*([\d.]+)\)/);
    if (hslaMatch) {
        const h = parseInt(hslaMatch[1]);
        const s = parseInt(hslaMatch[2]);
        const l = parseInt(hslaMatch[3]);
        return hslToHex(h, s, l);
    }
    
    // 处理RGB格式
    const rgbMatch = color.match(/rgb\((\d+),\s*(\d+),\s*(\d+)\)/);
    if (rgbMatch) {
        const r = parseInt(rgbMatch[1]).toString(16).padStart(2, '0');
        const g = parseInt(rgbMatch[2]).toString(16).padStart(2, '0');
        const b = parseInt(rgbMatch[3]).toString(16).padStart(2, '0');
        return r + g + b;
    }
    
    // 处理十六进制格式
    if (color.startsWith('#')) {
        return color.substring(1);
    }
    
    // 处理颜色名称
    const colorNameMap = {
        'red': 'E53E3E',
        'orange': 'DD6B20',
        'yellow': 'D69E2E',
        'green': '38A169',
        'blue': '3182CE',
        'purple': '805AD5',
        'pink': 'D53F8C',
        'gray': '718096',
        'brown': '8B4513',
        'black': '000000',
        'white': 'FFFFFF'
    };
    
    return colorNameMap[color.toLowerCase()] || '000000';
};

/**
 * 将HSL转换为十六进制
 * @param {number} h - 色相 (0-360)
 * @param {number} s - 饱和度 (0-100)
 * @param {number} l - 亮度 (0-100)
 * @returns {string} 十六进制颜色
 */
const hslToHex = (h, s, l) => {
    s /= 100;
    l /= 100;
    
    const c = (1 - Math.abs(2 * l - 1)) * s;
    const x = c * (1 - Math.abs((h / 60) % 2 - 1));
    const m = l - c / 2;
    let r = 0, g = 0, b = 0;
    
    if (0 <= h && h < 60) {
        r = c; g = x; b = 0;
    } else if (60 <= h && h < 120) {
        r = x; g = c; b = 0;
    } else if (120 <= h && h < 180) {
        r = 0; g = c; b = x;
    } else if (180 <= h && h < 240) {
        r = 0; g = x; b = c;
    } else if (240 <= h && h < 300) {
        r = x; g = 0; b = c;
    } else if (300 <= h && h < 360) {
        r = c; g = 0; b = x;
    }
    
    const rHex = Math.round((r + m) * 255).toString(16).padStart(2, '0');
    const gHex = Math.round((g + m) * 255).toString(16).padStart(2, '0');
    const bHex = Math.round((b + m) * 255).toString(16).padStart(2, '0');
    
    return rHex + gHex + bHex;
};

/**
 * 获取对齐方式
 * @param {string} textAlign - 文本对齐方式
 * @returns {AlignmentType} Word对齐方式
 */
const getAlignment = (textAlign) => {
    switch (textAlign) {
        case 'center':
            return AlignmentType.CENTER;
        case 'right':
            return AlignmentType.RIGHT;
        case 'justify':
            return AlignmentType.JUSTIFIED;
        default:
            return AlignmentType.LEFT;
    }
};

/**
 * 获取标题级别
 * @param {number} level - 标题级别
 * @returns {HeadingLevel} Word标题级别
 */
const getHeadingLevel = (level) => {
    switch (level) {
        case 1:
            return HeadingLevel.HEADING_1;
        case 2:
            return HeadingLevel.HEADING_2;
        case 3:
            return HeadingLevel.HEADING_3;
        case 4:
            return HeadingLevel.HEADING_4;
        case 5:
            return HeadingLevel.HEADING_5;
        case 6:
            return HeadingLevel.HEADING_6;
        default:
            return HeadingLevel.HEADING_1;
    }
};